package de.dubiel.plung.client.play;

import java.util.List;

import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.event.dom.client.GestureStartHandler;
import com.google.gwt.event.dom.client.MouseMoveHandler;
import com.google.gwt.event.dom.client.TouchMoveHandler;
import com.google.gwt.user.client.ui.FocusWidget;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;

import de.dubiel.plung.client.canvas.Drawable;

public class GamePanel extends HTMLPanel {

    private int width, height;
    private String backgroundcolor = "#fff";
    private Canvas canvas;
    private Context2d context;
    private boolean readyToUse;

    protected GamePanel(int width, int height) {
        super("");
        this.width = width;
        this.height = height;
        canvas = Canvas.createIfSupported();
        if (canvas == null) {
            this.add(new HTML("Canvas wird nicht unterst�tzt!"));
            return;
        }
        this.add(canvas);
        canvas.setSize(Integer.toString(width) + "px", Integer.toString(height) + "px");
        canvas.setCoordinateSpaceWidth(width);
        canvas.setCoordinateSpaceHeight(height);
        context = canvas.getContext2d();
        readyToUse = true;
    }

    public boolean isReadyToUse() {
        return readyToUse;
    }
    
    public String getBackgroundcolor() {
        return backgroundcolor;
    }

    public void setBackgroundcolor(String backgroundcolor) {
        this.backgroundcolor = backgroundcolor;
    }

    public void update(List<Drawable> objects) {
        context.setFillStyle(backgroundcolor);
        context.fillRect(0, 0, width, height);
        for (Drawable object : objects) {
            object.draw(context);
        }
    }

    /**
     * @see FocusWidget#addMouseMoveHandler(MouseMoveHandler)
     */
    public void addMouseMoveHandler(MouseMoveHandler handler) {
        if (isReadyToUse())
            canvas.addMouseMoveHandler(handler);
    }

    /**
     * @see FocusWidget#addTouchMoveHandler(TouchMoveHandler)
     */
    public void addTouchMoveHandler(TouchMoveHandler handler) {
        if (isReadyToUse())
            canvas.addTouchMoveHandler(handler);
    }

    /**
     * @see FocusWidget#addGestureStartHandler(GestureStartHandler)
     */
    public void addGestureStartHandler(GestureStartHandler handler) {
        if (isReadyToUse())
            canvas.addGestureStartHandler(handler);
    }
}
